﻿$().ready(function () {
    $("#optPosition").attr("class", "HoverOnList");
    $("#breadcrumb").append('<li><a href="' + $("#urlPosition").val() + '" title="Posiciones">Posiciones</a></li>');

    $.datepicker.regional['es'] = {
        closeText: 'Cerrar',
        prevText: '<Ant',
        nextText: 'Sig>',
        currentText: 'Hoy',
        monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
        monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
        dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
        dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mié', 'Juv', 'Vie', 'Sáb'],
        dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
        weekHeader: 'Sm',
        dateFormat: 'dd/mm/yy',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''
    };
    $.datepicker.setDefaults($.datepicker.regional['es']);

    $("#txtEstimatedStartDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

    $("#txtEstimatedEndDate").datepicker({
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });


    $('.item-del').live('click', function () {
        if (confirm('¿Esta seguro que desea eliminar el registro?')) {
            $(this).closest('li').remove();
        }
    });


    ///Toolbar
    $('#btnClear').live('click', function () {
        ClearForm();
    });


    $('#btnSave').click(function () {
        if ($("#frmPositionResponsability").valid()) {

            var list = new Array();
            $('#lstResponsabilities li').each(function () {
                var current = $(this);
                var item = current.attr("responsabilityTypeID") + ";" + current.attr("description");
                list.push(item);
            });

            if (list.length > 0) {
                Add();
            }
            else {
                alert('Debe ingresar al menos un producto al listado');
            }
        }
    });

    $('#btnAddResponsability').live('click', function () {
        AddRecord();
    });

    $('#btnNew').live('click', function () {
        if (confirm('¿Desea abandonar la edición y crear un registro nuevo?')) {
            window.location = $('#urlCreate').val();
        }

    });

    ///Menu
    $('#menuClear').live('click', function () {
        ClearForm();
    });

    $('#menuNew').live('click', function () {
        if (confirm('¿Desea abandonar la edición y crear un registro nuevo?')) {
            window.location = $('#urlCreate').val();
        }
    });
    $('#btnSearch').click(function () {
        Search();
    });
    if (!(typeof $('#txtPersonFilter')[0] === "undefined")) {
        InitAutocomplete();
    }


});

function ConfirmDelete(id) {
    if (confirm('¿Esta seguro que desea eliminar el registro?')) {
        Delete(id);
    }
}

function Delete(objectId) {
    $.ajax(
    {
        type: "POST",
        url: $('#urlDelete').val(),
        data:
            JSON.stringify({
                id: objectId
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = "/ODSYSUI/Position/SetMessage?id=1";
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            window.location = "/ODSYSUI/Position/SetMessage?id=2";
        }
    });
}

function ClearForm() {
    //Limpia los textbox
    $('#txtID').val('');
    $('#txtTitle').val('');
    $('#txtEstimatedStartDate').val('');
    $('#txtEstimatedEndDate').val('');
    $('#txtDescription').val('');


    //Remueve todos los mensajes de error que genera el framework
    $('.field-validation-error').remove();
    $(":input").removeClass("input-validation-error");
}

function Search() {
    var startDate = $('#txtStartDate').val();
    var endDate = $('#txtEndDate').val();
    var date1 = null;
    var date2 = null;

    if (startDate != "") {
        var d1 = parseInt(startDate.substring(0, 2));
        var m1 = parseInt(startDate.substring(3, 5)) - 1;
        var y1 = parseInt(startDate.substring(6, 10));
        date1 = new Date(y1, m1, d1);
    }

    if (endDate != "") {
        var d1 = parseInt(endDate.substring(0, 2));
        var m1 = parseInt(endDate.substring(3, 5)) - 1;
        var y1 = parseInt(endDate.substring(6, 10));
        date2 = new Date(y1, m1, d1);
    }

    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlSearch").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                name: $('#txtName').val(),
                startDate: date1,
                endDate: date2,
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = $("#urlSearch").val();
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {

            //window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=2";
        }
    });
}

function AddRecord() {
    if ($("#frmPositionResponsability").valid()) {

        var list = new Array();
        $('#lstResponsabilities li').each(function () {
            var current = $(this);
            if($('#cmbResponsabilityType').val() == current.attr("responsabilityTypeID"))
            { 
                list.push(item);
            }
        });

        if (list.length == 0)
        {
                var item = "<li responsabilityTypeID='" + $('#cmbResponsabilityType').val() + "' description='" + $('#txtResponsabilityDescription').val() + "'>" +
                                "<table style='width: 100%;'>" +
                                    "<tr>" +
                                        "<td style='width: 14%; text-align: left;'>" + $('#cmbResponsabilityType>option:selected').text() + "</td>" +
                                        "<td style='width: 65%; text-align: left;'>" + $('#txtResponsabilityDescription').val() + "</td>" +
                                    "</tr>" +
                                 "</table>" +
                                 "<img class='item-del' width='16' height='16' src='/ODSYSUI/Content/images/icons/fugue/Delete.png' style='float: right; vertical-align: middle; margin-top: -15px; margin-left: 15px; cursor: pointer; border: 0px;'>" +
                            "</li>";

                $("#ResponsabilitiesList ul").append(item);
        }
        else
        {
            alert('La responsabilidad ya ha sido insertada');
        }
        //   Clear();
    }

    else {
        alert('Debe seleccionar un tipo de responsabilidad.');
    }
}

function Add() {
    var list = new Array();
    $('#lstResponsabilities li').each(function () {
        var current = $(this);
        var item = current.attr("responsabilityTypeID") + ";" + current.attr("description");
        list.push(item);
    });

    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlCreate").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                title: $("#txtTitle").val(),
                positionStatusID: $("#cmbPositionStatus").val(),
                estimatedStartDate: $("#txtEstimatedStartDate").val(),
                estimatedEndDate: $("#txtEstimatedEndDate").val(),
                positionTypeID: $("#cmbPositionType").val(),
                exempt: $("#chkExent").val(),
                fullTime: $("#chkFullTime").val(),
                temporary: $("#chkTemporal").val(),
                salary: $("#chkSalary").val(),
                items: list

            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                // window.location = $("#urlPrint").val();
                window.location = "/ODSYSUI/Position/SetMessage?id=3";
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            window.location = "/ODSYSUI/Position/SetMessage?id=4";
        }
    });
}

